#include "udpsocketgroup.h"

UdpSocketGroup::UdpSocketGroup(const QString mac)
{
    m_mac = mac;
    QList<QNetworkInterface> list = QNetworkInterface::allInterfaces();

    for(int i = 0; i < list.count(); i++)
    {
        qDebug() << "index = " << list.at(i).index() << ", mac = " <<  list.at(i).hardwareAddress();
        if(list.at(i).hardwareAddress() == mac && mac != "")
        {
            _thisNet = list.at(i);
            qDebug() << "_thisNet selected....";
            break;
        }
    }

    connect(_sock,&QUdpSocket::readyRead,this,[this]()
    {
        while(_sock->hasPendingDatagrams())
        {
            QByteArray datagram;
            datagram.resize(_sock->pendingDatagramSize());
            QHostAddress peerAddr;
            quint16 peerPort;
            _sock->readDatagram(datagram.data(),datagram.size(),&peerAddr,&peerPort);

            emit signal_readMsg(peerAddr.toString(),peerPort,datagram);
        }
    });
}

bool UdpSocketGroup::bind_multicast(QHostAddress ip, uint16_t port)
{
    _groupAddress = QHostAddress(ip);
    _groupPort = port;

    qDebug() << "_groupAddress: " << _groupAddress;
    qDebug() << "_groupPort: " << _groupPort;

    if(!_sock->bind(QHostAddress::AnyIPv4, port, QUdpSocket::ShareAddress))
    {
        isConnecting = false;
        qDebug() << "UDPSocket 绑定失败...";
        return false;
    }

    qDebug() << "this mac: " << _thisNet.hardwareAddress();

    _sock->setSocketOption(QAbstractSocket::MulticastTtlOption, 2);
    _sock->setMulticastInterface(_thisNet);

    if(!_sock->joinMulticastGroup(_groupAddress,_thisNet))
    {
        isConnecting = false;
        qDebug() << "UDPSocket 组播连接失败..." << _sock->errorString();

        return false;
    }

    isConnecting = true;
    qDebug() << "UDPSocket 组播 连接成功...";
    return true;

}

void UdpSocketGroup::quit_multicast()
{
    _sock->leaveMulticastGroup(_groupAddress);// 退出组播
    _sock->abort();
    isConnecting = false;
    qDebug() << "UDPSocket 组播 关闭连接...";
}

qint64 UdpSocketGroup::send_msg(QByteArray msg, QString addr, int port)
{
    //qDebug() << "### send addr: " << addr << ", port = " << port;
    return _sock->writeDatagram(msg,QHostAddress(addr),port);
}
